package org.luckystrophe.snowtoms.fragment;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.luckystrophe.snowtoms.R;
import org.luckystrophe.snowtoms.model.CoachMarks;
import org.luckystrophe.snowtoms.model.JsonRequest;
import org.luckystrophe.snowtoms.model.impl.CoachMarksImpl;
import org.luckystrophe.snowtoms.model.impl.District;
import org.luckystrophe.snowtoms.model.impl.GetRankRequest;
import org.luckystrophe.snowtoms.pref.AppPreference_;

import android.graphics.drawable.AnimationDrawable;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockFragment;
import com.googlecode.androidannotations.annotations.AfterInject;
import com.googlecode.androidannotations.annotations.AfterViews;
import com.googlecode.androidannotations.annotations.Background;
import com.googlecode.androidannotations.annotations.Bean;
import com.googlecode.androidannotations.annotations.EFragment;
import com.googlecode.androidannotations.annotations.UiThread;
import com.googlecode.androidannotations.annotations.ViewById;
import com.googlecode.androidannotations.annotations.sharedpreferences.Pref;

@EFragment(R.layout.fragment_rank)
public class RankFragment extends SherlockFragment implements OnTouchListener, AnimationListener {

	@ViewById(R.id.rl_mainSize)
	RelativeLayout rl_mainSize;

	@ViewById(R.id.tv_districtrank)
	TextView distictRank;

	@ViewById(R.id.btn_snoweffect)
	Button snowEffect;

	@ViewById(R.id.iv_fallingsnow)
	ImageView iv_fallingSnow;

	@Bean(GetRankRequest.class)
	JsonRequest jsonRequest;

	@Pref
	AppPreference_ appPref;

	@Bean(CoachMarksImpl.class)
	CoachMarks coachMarks;

	AnimationDrawable fallingSnowAnimation;

	private Animation decreaseScale;

	public static int TICK_HEIGHT = 0;

	public static int TICK_COUNT = 0;

	public static ArrayList<District> districtArray;

	private int startYPoint = 0;

	private int currentDistrict = 0;

	private District bestDistrict;

	public static ArrayList<int[]> colorBackgrounds = new ArrayList<int[]>();

	@AfterInject
	public void afterInject() {
		coachMarks.showCoachMark(getSherlockActivity(), CoachMarks.COACH_MARK_1, appPref.isShowRankFragment());
		getRanking();
		decreaseScale = AnimationUtils.loadAnimation(getSherlockActivity(), R.anim.anim_decreasescale);
		decreaseScale.setAnimationListener(this);
	}

	@Background
	public void getRanking() {
		try {
			afterGetRanking(jsonRequest.sendJsonRequest());
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@UiThread
	public void afterGetRanking(JSONObject resultJo) {
		try {
			JSONArray districtJArray = ((GetRankRequest) jsonRequest).parseResultJson(resultJo);
			districtArray = new ArrayList<District>();
			int guListLength = districtJArray.length();
			for (int i = 0; i < guListLength; i++) {
				JSONObject detailDistrict = districtJArray.getJSONObject(i);
				districtArray.add(new District(detailDistrict.getInt("id"), i + 1, 0, detailDistrict
						.getString("areaname")));
			}
			bestDistrict = districtArray.get(0);
			setRanking();
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	@UiThread
	public void setRanking() {
		if (bestDistrict != null) {
			distictRank.setText("" + bestDistrict.getDistrictRanking() + "위\n" + bestDistrict.getDistrictNameHangul());
		}
	}

	@AfterViews
	public void afterView() {
		getSherlockActivity().getSupportActionBar().setTitle(R.string.actionbarTitleRanking);
		rl_mainSize.setOnTouchListener(this);
		setRanking();
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		int actionCode = event.getAction();
		int nowPosition = (int) event.getY();

		if (actionCode == MotionEvent.ACTION_DOWN) {
			startYPoint = (int) event.getY();
			snowEffect.clearAnimation();
		}

		if (actionCode == MotionEvent.ACTION_MOVE) {

			if (startYPoint < nowPosition) {
				currentDistrict = changeViews((nowPosition - startYPoint) / TICK_COUNT);

				distictRank.setText("" + districtArray.get(currentDistrict).getDistrictRanking() + "위\n"
						+ districtArray.get(currentDistrict).getDistrictNameHangul());

				if (currentDistrict > 0) {
					snowEffect.setVisibility(View.VISIBLE);
					snowEffect.setHeight((currentDistrict + 1) * TICK_HEIGHT);
				}

			} else {
				distictRank.setText("" + bestDistrict.getDistrictRanking() + "위\n"
						+ bestDistrict.getDistrictNameHangul());
				snowEffect.setVisibility(View.INVISIBLE);

			}
		}

		if (actionCode == MotionEvent.ACTION_UP) {
			if (currentDistrict > 0 && startYPoint < nowPosition) {
				startPileSnow();
			}
		}
		return true;
	}

	@UiThread
	public void startPileSnow() {
		snowEffect.startAnimation(decreaseScale);
		snowEffect.setVisibility(View.INVISIBLE);
	}

	private int changeViews(int index) {
		return index > 24 ? 24 : index;
	}

	@Override
	public void onAnimationEnd(Animation animation) {
		distictRank.setText("" + bestDistrict.getDistrictRanking() + "위\n" + bestDistrict.getDistrictNameHangul());
	}

	@Override
	public void onAnimationRepeat(Animation animation) {
	}

	@Override
	public void onAnimationStart(Animation animation) {
	}

	@SuppressWarnings("deprecation")
	@UiThread
	public void startFallingSnow() {
		fallingSnowAnimation = new AnimationDrawable();

		fallingSnowAnimation.addFrame(getResources().getDrawable(R.drawable.snowfalling_1), 400);
		fallingSnowAnimation.addFrame(getResources().getDrawable(R.drawable.snowfalling_2), 400);

		fallingSnowAnimation.setOneShot(false);
		iv_fallingSnow.setBackgroundDrawable(fallingSnowAnimation);
		iv_fallingSnow.post(new AnimationStater());
	}

	public class AnimationStater implements Runnable {
		@Override
		public void run() {
			fallingSnowAnimation.start();
		}

	}

	@Override
	public void onStop() {
		super.onStop();
		fallingSnowAnimation.stop();
	}

	@Override
	public void onResume() {
		super.onResume();
		startFallingSnow();
	}
}
